<script lang="ts" setup>
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetAftersalesApplyList, PostApplyAudit } from '@/api/modules/aftersales'
import GetCacheData from '@/store/modules/NewPageCache'

// const imgDomain = 'https://img1.eprhan.cc'
// const router = useRouter()
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('aftersalesApply').currentPage

const ruleFormRef = ref<FormInstance>()

const findFrom = ref({
  ...(cacheData.GetCacheData('aftersalesApply').fromData),
})
const dataList: any = reactive({
  list: [],
})
const loading = ref(true)
const total = ref(0)

// const waybillStatusOption = {
//   0: '已下单待揽件',
//   1: '已揽件',
//   2: '运输中',
//   3: '派件中',
//   4: '已签收',
//   5: '异常',
//   6: '代签收',
//   7: '揽收失败',
//   8: '签收失败（拒收、超区）',
//   11: '已取消',
//   13: '退件中',
//   14: '已退件',
//   99: '未知',
// }
const applyStatusOption = {
  0: '退货申请待审核',
  2: '退货申请驳回',
  3: '创建退货ID失败',
  10: '退货退款待审核',
  11: '退货退款审核成功',
  12: '退货退款驳回',
  13: '退款失败',
  14: '理赔失败',
}

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.OrderNo && ({ OrderNo: findFrom.value.OrderNo })),
    ...(findFrom.value.WaybillId && ({ WaybillId: findFrom.value.WaybillId })),
    ...(findFrom.value.DeliveryName && ({ DeliveryName: findFrom.value.DeliveryName })),
    ...(findFrom.value.IsRefuse !== '~' && ({ IsRefuse: findFrom.value.IsRefuse })),
    ...(findFrom.value.ApplyStatus !== '~' && ({ ApplyStatus: findFrom.value.ApplyStatus })),
  }
  await GetAftersalesApplyList(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      loading.value = false
      ElMessage.error(`获取数据失败。${dataRes.errors}`)
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('aftersalesApply').currentSize)
  cacheData.SetCacheData('aftersalesApply', PageNum, cacheData.GetCacheData('aftersalesApply').currentSize, findFrom.value)
}

// 图片预览
const srcList = ref([])

function handlePreview(row: any) {
  srcList.value = (row.pictures.split(',')).map((url: string) => url)
}

// 退款申请审核
const dialogFormVisible = ref(false)

const bizOption = [
  { label: '山东省-济南市-济阳区-崔寨街道阳光幕墙东北济南崔寨物流园', value: 1 },
  { label: '新疆维吾尔自治区-乌鲁木齐市-新市区-北京路街道 北京北路4889号中通总部3号快递园区云仓2楼', value: 2 },

]
const RefundFrom = reactive<
  {
    id: number
    auditStatus: boolean
    bizAddr: number | ''
    auditReason: string
    orderNo?: string
    isRefuse?: number
    returnReason?: string
    pictures?: string
    ApplyStatus?: number

  }>({
  id: 0,
  auditStatus: false,
  bizAddr: '',
  auditReason: '',
  ApplyStatus: 0,
})

const rules = reactive({
  bizAddr: [
    { required: true, message: '请选择退货地址', trigger: 'blur' },
  ],
  auditReason: [
    { required: true, message: '请输入审核驳回原因', trigger: 'blur' },
  ],
})

function SetRefundData(item: any) {
  RefundFrom.id = item.id
  RefundFrom.ApplyStatus = item.ApplyStatus
  RefundFrom.orderNo = item.orderNo
  RefundFrom.isRefuse = item.isRefuse
  RefundFrom.auditStatus = item.auditStatus
  RefundFrom.returnReason = item.returnReason
  RefundFrom.pictures = item.pictures
  dialogFormVisible.value = true
}

async function RefundApply(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        '你确定要通过该审核吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        },
      )
        .then(() => {
          const params = {
            id: RefundFrom.id,
            auditStatus: RefundFrom.auditStatus,
            auditReason: RefundFrom.auditReason,
            bizAddr: RefundFrom.bizAddr === 1
              ? '{"name":"欧亭亭","mobile":"15969691033","country":"中国","province":"山东省","city":"济南市","area":"济阳区","address":"崔寨街道阳光幕墙东北济南崔寨物流园"}'
              : RefundFrom.bizAddr === 2
                ? '{"name":"李万虎","mobile":"18199868147","country":"中国","province":"新疆维吾尔自治区","city":"乌鲁木齐市","area":"新市区","address":"北京路街道 北京北路4889号中通总部3号快递园区云仓2楼"}'
                : '',
          }
          // console.log(params)
          PostApplyAudit(params).then(async (dataRes: any) => {
            if (dataRes.succeeded) {
              ElMessage.success('审核成功')
              GetDataList(cacheData.GetCacheData('aftersalesApply').currentPage, cacheData.GetCacheData('aftersalesApply').currentSize)
              dialogFormVisible.value = false
              RefundFrom.auditStatus = false
              RefundFrom.auditReason = ''
              RefundFrom.bizAddr = ''
            }
            else {
              if (typeof dataRes.errors === 'string') {
                ElMessage.error(`审核失败。${dataRes.errors}`)
              }
              else {
                let errorStr = ''
                for (const key in dataRes.errors) {
                  errorStr += `${key}：${dataRes.errors[key]}；`
                }
                ElMessage.error(`审核失败。${errorStr}`)
              }
            }
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消',
          })
        })
    }
  })
}

// 审核通过
function AuditPass(item: any) {
  const params = {
    id: item.id,
    auditStatus: true,
    auditReason: '',
    bizAddr: '',
  }

  PostApplyAudit(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      ElMessage.success('审核成功')
      GetDataList(cacheData.GetCacheData('aftersalesApply').currentPage, cacheData.GetCacheData('aftersalesApply').currentSize)
    }
    else {
      if (typeof dataRes.errors === 'string') {
        ElMessage.error(`审核失败。${dataRes.errors}`)
      }
      else {
        let errorStr = ''
        for (const key in dataRes.errors) {
          errorStr += `${key}：${dataRes.errors[key]}；`
        }
        ElMessage.error(`审核失败。${errorStr}`)
      }
    }
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('aftersalesApply', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('aftersalesApply').currentSize)
  cacheData.SetCacheData('aftersalesApply', val, cacheData.GetCacheData('aftersalesApply').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('aftersalesApply').currentPage || 1
})

onMounted(async () => {
  GetDataList(cacheData.GetCacheData('aftersalesApply').currentPage, cacheData.GetCacheData('aftersalesApply').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="订单编号">
                <el-input v-model="findFrom.OrderNo" placeholder="请输入订单编号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="售后类型">
                <el-select v-model="findFrom.IsRefuse" placeholder="请选择售后类型">
                  <el-option label="不限" value="~" />
                  <el-option label="申请拒收退款" :value="1" />
                  <el-option label="申请退货退款" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item label="退货运单号">
                <el-input v-model="findFrom.WaybillId" placeholder="请输入退货运单号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="运力公司名称">
                <el-input v-model="findFrom.DeliveryName" placeholder="请输入运力公司名称" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.ApplyStatus" placeholder="请选择售后类型">
                  <el-option label="不限" value="~" />
                  <el-option v-for="(item, key) in applyStatusOption" :key="key" :label="item" :value="key" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <!-- <el-button type="success" @click="AddData">
          添加
        </el-button> -->
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="orderNo" label="订单编号" width="300" />
        <el-table-column align="center" prop="kuaiDiDanHao" label="发货运单号" width="300" />
        <el-table-column header-align="center" prop="waybillId" label="退货运单号" width="300" />
        <el-table-column align="center" prop="isRefuse" label="售后类型" width="130">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.isRefuse === 0 ? '申请退货退款'
                : scope.row.isRefuse === 1 ? '申请拒收退款' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="applyStatus" label="状态" width="160">
          <template #default="scope">
            <el-tag type="primary">
              {{ applyStatusOption[scope.row.applyStatus as keyof typeof applyStatusOption] || '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="returnReason" label="售后原因" width="300" />
        <el-table-column header-align="center" prop="pictures" label="售后凭证" min-width="300">
          <template #default="scope">
            <span v-if="scope.row.pictures === ''">无</span>
            <el-scrollbar v-else>
              <div class="scrollbar-flex-content">
                <el-image
                  v-for="(item, index) in scope.row.pictures.split(',')"
                  :key="index"
                  class="scrollbar-flex-img"
                  :src="item"
                  :preview-src-list="srcList"
                  :initial-index="index"
                  :preview-teleported="true"
                  @click="handlePreview(scope.row)"
                />
              </div>
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="shopOrderId" label="退货编号" width="300" />
        <el-table-column align="center" prop="returnId" label="退货ID" width="300" />
        <!-- <el-table-column align="center" prop="pictures" label="售后凭证" width="300"> -->
        <!-- <el-table-column align="center" prop="bizAddr" label="退货地址" width="300" /> -->
        <el-table-column align="center" prop="auditReason" label="审核驳回原因" width="200" />
        <el-table-column align="center" prop="applyAuditTime" label="退货申请审核时间" width="230" />
        <el-table-column align="center" prop="auditTime" label="退货退款审核时间" width="230" />
        <el-table-column align="center" prop="returnType" label="退货类型" width="130">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.returnType === 0 ? '未填写'
                : scope.row.returnType === 1 ? '上门取件' : scope.row.returnType === 1 ? '自行寄回' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="deliveryId" label="运力公司编码" width="300" />
        <el-table-column header-align="center" prop="deliveryName" label="运力公司名称" width="150" />
        <!-- <el-table-column align="center" prop="waybillStatus" label="运单状态" width="120">
          <template #default="scope">
            <span v-if="scope.row.returnId === ''" />
            <el-tag v-else type="primary">
              {{ waybillStatusOption[scope.row.waybillStatus as keyof typeof waybillStatusOption] || '未定义' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column header-align="center" prop="desp" label="备注" width="460">
          <template #default="scope">
            <el-scrollbar height="60px">
              {{ scope.row.desp }}
            </el-scrollbar>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addTime" label="申请时间" width="230" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="230" />
        <el-table-column align="center" label="操作" fixed="right" min-width="200">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="primary" :disabled="scope.row.applyStatus !== 0 && scope.row.applyStatus !== 10" @click="SetRefundData(scope.row)">
                {{ scope.row.applyStatus === 0 ? '申请售后审核' : '退货退款审核' }}
              </el-button>
              <el-button v-if="scope.row.applyStatus === 13" type="primary" @click="AuditPass(scope.row)">
                审核通过
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('aftersalesApply').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>

    <el-dialog v-model="dialogFormVisible" title="退款申请审核" width="500">
      <el-form ref="ruleFormRef" :model="RefundFrom" :rules="rules">
        <el-form-item label="订单编号：" label-width="110px">
          {{ RefundFrom.orderNo ? RefundFrom.orderNo : '无' }}
        </el-form-item>
        <el-form-item label="售后类型：" label-width="110px">
          {{ RefundFrom.isRefuse === 0 ? '申请退货退款'
            : RefundFrom.isRefuse === 1 ? '申请拒收退款' : '未定义' }}
        </el-form-item>
        <el-form-item label="售后原因：" label-width="110px">
          {{ RefundFrom.returnReason ? RefundFrom.returnReason : '无' }}
        </el-form-item>
        <el-form-item label="售后凭证：" label-width="110px">
          <div class="scrollbar-flex-content">
            <el-image
              v-for="(item, index) in RefundFrom.pictures?.split(',')"
              :key="index"
              class="scrollbar-flex-img"
              :src="item"
              :preview-src-list="srcList"
              :initial-index="index"
              :preview-teleported="true"
              @click="handlePreview(RefundFrom)"
            />
          </div>
        </el-form-item>
        <el-form-item label="审核是否通过" prop="auditStatus" label-width="110px">
          <!-- <el-switch v-model="RefundFrom.auditStatus" /> -->
          <el-radio-group v-model="RefundFrom.auditStatus">
            <el-radio :value="true">
              通过
            </el-radio>
            <el-radio :value="false">
              不通过
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退货地址" :prop="RefundFrom.auditStatus ? 'bizAddr' : ''" label-width="110px">
          <!-- <PcasCascader v-model="RefundFrom.bizAddr" format="name" /> -->
          <el-select v-model="RefundFrom.bizAddr" placeholder="请选择退货地址" style="width: 240px;">
            <el-option
              v-for="item in bizOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核驳回原因" :prop="RefundFrom.auditStatus ? '' : 'auditReason'" label-width="110px">
          <el-input v-model="RefundFrom.auditReason" placeholder="请填写审核驳回原因" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="RefundApply(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 60px;
    margin-right: 10px;
  }
}
</style>
